package com.mycompany.oj.util;

import com.mycompany.oj.Mapper.Impl.MyQuestionJudgeMapperImpl;
import com.mycompany.oj.entity.FileUtils;
import com.mycompany.oj.service.Impl.LoginServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * @author asus
 */
@Service
public class SharedService {

    @Autowired
    MyQuestionJudgeMapperImpl questionJudgeMapper;
    @Autowired
    MyQuestionJudgeMapperImpl questionmapper;


    @Value("${jwt.secret}")
    private String secret;

    private JwtUtils jwtUtils = new JwtUtils();

    public boolean judgeAdmin(String token) throws Exception {
        Date date = new Date();
        String strDateFormat = "yyyyMMddHHmmss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String time = sdf.format(date);
        long oldTime = Long.parseLong(jwtUtils.parseJWT(token, secret).get("time").toString());
        Long now = sdf.parse(time).getTime();
        long day = now - oldTime;
        if (day >= 3) {
            return false;
        }
        return true;
    }


    public String getUsername(HttpServletRequest request) throws Exception {
        return jwtUtils.parseJWT(request.getHeader("Authorization"), secret).get("username").toString();
    }

    public String getAccountId(String username) {
        String account_id = questionJudgeMapper.getAccountId(username).get(0).get("id").toString();
        return account_id;
    }

    public String getAccountIdBySchoolid(String schoolid) {
        String account_id = questionJudgeMapper.getAccountIdbyschoolid(schoolid).get(0).get("id").toString();
        return account_id;
    }

    public String check1(String username) {
        return Optional.ofNullable(username).orElse("空");
    }

    //判断是否为空
    public void check2(List<Map<String, Object>> temp) {
        if (temp.size() == 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("number", "0");
            temp.add(map);
        }
    }

    public List<Map<String, Object>> check4(List<Map<String, Object>> temp) {
        if (temp.size() == 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("number", "0");
            temp.add(map);
            return temp;
        }
        return temp;
    }

    //判断数组是否为空
    public boolean check3(String[] temp) {
        List<String> list = Arrays.asList(temp);
        if (list.isEmpty()) {
            return false;
        }
        //不空
        return true;
    }

    //获取蓝桥题库测试的通过率
    public double getAC(int aa) {
        String id = Integer.toString(aa);
        List<Map<String, Object>> temp = questionmapper.calculateAC(id);
        String num1 = temp.get(0).get("number").toString();
        String num2 = temp.get(1).get("number").toString();
        if (Integer.parseInt(num1) == 0) {
            return 0;
        }
        return (double) Integer.parseInt(num2) / Integer.parseInt(num1);
    }

    public void mapToObject(Object object, Map<String, Object> map) {
        List<Field> objectAttribute = Arrays.asList(object.getClass().getDeclaredFields());
        Iterator<String> iter = map.keySet().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            objectAttribute.stream().forEach(x -> {
                String value = map.get(key).toString();
                if (x.getName().equals(key)) {
                    try {
                        x.set(object, value);
                    } catch (IllegalArgumentException ex) {
//                        Logger.getLogger(getAttribute.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IllegalAccessException ex) {
//                        Logger.getLogger(getAttribute.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            });
        }
    }

    //上传文件
    public String fileUp(String Account_id, MultipartFile file, String localPath) {
        SimpleDateFormat df = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");//设置日期格式
        String filename = Account_id + df.format(new Date()) + ".png";// new Date()为获取当前系统时间
        if (FileUtils.upload(file, localPath, filename)) {
            String ppp = "images/" + filename;
            String shPath = "/root/per.sh";
            Process ps = null;
            try {
                ps = Runtime.getRuntime().exec(shPath);
            } catch (IOException ex) {
                Logger.getLogger(LoginServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                ps.waitFor();
            } catch (InterruptedException ex) {
                Logger.getLogger(LoginServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
            return filename;
        }
        return "false";

    }
}
